<?php
namespace Wap\Controller;
use Think\Controller;
use Wap\Controller\WapController;

class OrderFoodController extends WapController {
	public $weObj;
	public $startTime;	// 这期的开始时间
	public $endTime;	// 这期的结束时间, 用于是否在这期中已经点菜过
	public $canOrder;
	public $sendTime;
	public $signpackage;
	public $isCheckOp;
	public function _initialize() {
		parent::_initialize();
		$self_url = __SELF__;
		$aeq_pos = stripos($self_url, 'a=');
		$op_name = substr($self_url, $aeq_pos+2);
		\Think\Log::write("signature");
		$this->signpackage = getWXJsSign();
	}
	
	public function index() {
		\Think\Log::write("C_SITE_URL = " .__MODULE__);
		//$this->timeOKCheck();
		$fsorts = M('food_sort')->select();
		$foods = array();
		foreach($fsorts as $fsort) {
			$condition = array('sid' => $fsort['id']);
			$foodstmp = M('food')->where($condition)->select();
			$foods[$fsort['id']] = array('foods' => $foodstmp, 'sort'=>$fsort);
		}
		
		$this->assign('fsorts', $fsorts);
		$this->assign('maxCount', 7);
		$this->assign('foods', $foods);
		$this->assign('kconoff', C('kconoff'));
		$this->assign('metaTitle', C('pom_type_name'));
		\Think\Log::write("显示菜单");
		$this->display();
	}
	
	// 确定订单
	public function sureOrder() {
		\Think\Log::write("订单确认 U = ".U('Wap/OrderFood/sureOrder',array('openid' => 'abc'), false));
		$today = date("Y-m-d");
		$zero_clock_sec  = strtotime($today);
		$midnight_clock_sec   = time(date("Y-m-d"))+24*60*60-1;
		
		$outset = array("zc_sdate" 	=> $zeroClockSec, 		// 营业开始时间
						"zc_edate" 	=> $midnitClockSec,		// 营业截止时间
						"permin"  	=> 15,						// 间隔15分钟作为一段让用户选择送达时间
						"sendtime"	=> 30,						// 送达时间，30分钟内送达
				);	
		/* 计算输出的送达时间 */
        $permin = $outset['permin'] > 0 ? $outset['permin'] : 15;
        $sendtime = $outset['sendtime'] > 0 ? $outset['sendtime'] : $permin;
        $starttime = $current = time();
        if (($outset['zc_sdate'] > 0) && ($current < $outset['zc_sdate'])) {
        	Log::write("进行设置");
            $starttime = $outset['zc_sdate'];
			$starttime = date('Y-m-d').' '.date('H:i:s', $outset['zc_sdate']);
			$starttime = strtotime($starttime);
        }
        $endtime = strtotime(date('Y-m-d ') . "23:59:59");
        if ($outset['zc_edate'] > 0) {
            $endtime = $outset['zc_edate'];
			$endtime = date('Y-m-d').' '.date('H:i:s', $outset['zc_edate']);
			$endtime = strtotime($endtime);
        }
        $starttime = $starttime + ($sendtime * 60);
        $t1 = strtotime(date('Y-m-d H', $starttime) . ":00:00");
        $t2 = $starttime - $t1;
        $t3 = $permin * 60;
        $t4 = $sendtime * 60;
        if ($t2 < $t3) {
            $starttime = $t1 + $t3;
        } elseif ($t2 > $t4) {
            $starttime = $t1 + $t4 + $t3;
        } else {
            $starttime = $t1 + (2 * $t3);
        }
        $tmptime = $endtime - $starttime;
        if ($tmptime > 0) {
            $mins = floor($tmptime / 60);
            $timearr[] = date('H:i', $starttime);
            if ($mins > $permin) {
                for ($i = $permin; $i <= $mins; $i = $i + $permin) {
                    $timearr[] = date('H:i', ($i * 60 + $starttime));
                }
            }
        } else {
            $timearr[] = date('H:i', $endtime);
        }
		
		$this->assign('timearr', $timearr);
		\Think\Log::write("送达时间 timearr => ".dump($timearr, false));
		
		//$this->timeOKCheck();
		$nums = 0;
		$totalPrice = 0;
		$foods = array();
		foreach($_POST['foods'] as $k => $food) {
			if($food >= 1) {
				$tmpfood = M('food')->where(array('id'=>$k))->find();
				$tmpfood['num'] = $food;
				$nums = $nums + $food;
				$totalPrice += $tmpfood['price']*$food;
				$foods[] = $tmpfood;
			}
		}
		$this->assign('foods', $foods);
		$this->assign('nums', $nums);
		$this->assign('totalPrice', $totalPrice);
		$this->assign('sendTime', $this->sendTime);
		$this->assign('metaTitle', '确认订单');
		$this->assign('userinfo', $this->userinfo);
		$this->display();
	}
	
	// 提交订单	
	public function submitOrder() {
		\Think\Log::write("参数=》". dump($_POST, false));
		//$this->timeOKCheck();
		\Think\Log::write("submit order openid =>".$this->openid);
		$oid 		= time().substr(microtime(),2,6).rand(0,9);
		$ofoods 	= serialize($_POST['foods']);
		$state 		= C('UNSEND');	// 0 未发货 1 已发货 2 用户已收货
		$istmsg 	= 0; 	// 0 未发送 已发货模板消息
		$mark		= $_POST['omark'];
		$addtime 	= time();
		$deliverytime = $_POST['oarrivalTime'];
		// windows操作系统有 strtotime(date("Y-m-d"))零点是7点钟
		if(!empty($deliverytime)) {
			$tmpDlvryTime = strtotime(date("Y-m-d").' ' .$deliverytime);
		} else {
			$tmpDlvryTime = null;
		}
		
		$odata = array(
			'oid'		=> $oid,
			'openid'	=> $this->openid,
			'ofoods'	=> $ofoods,
			'state'		=> $state,	// 未发货
			'istmsg'	=> $istmsg,
			'mark'		=> $mark,
			'addtime'	=> $addtime,
			'sendtime'	=> '',
			'deliverytime' => $tmpDlvryTime,
		);
		$addRes = M('order')->add($odata); 
		$this->assign('title', '提示');
		$this->assign('msg', '订单提交成功！'.C('pom_order_done_message'));
		$this->assign('icontype', C('ICON_DONE'));
		$this->assign('signpackage', $this->signpackage);
		
		$username = $_POST['ouserName'];
		$address  = $_POST['ouserAddres'];
		$usersex  = $_POST['ouserSex'];
		$tel	  = $_POST['ouserTel'];
		$pdata = array("address" => $address, "tell" => $tel, "truename" => $username, "psex" => $usersex);
		\Think\Log::write("插入的收货地址：".dump($pdata, false));
		$condition = array("openid" => $this->openid);
		// 更新收货地址
		$updatePostRes = M('wxuser')->where($condition)->save($pdata);
		
		$totalnum = trim($_POST['totalnum']);
		// 发送模板消息
		/*
		$data = array("touser"=>"$this->openid",
						"template_id"=>"4e_1ebW7M6iYe2dOrJ-TzXpdwcFnN-J_HMkpGIQTcZ0",
						"url"=> C('site_url').'/'.U('Wap/OrderFood/myOrder'),
						"topcolor"=>"#FF0000",
						"data"=> array( "first"=>array("value"=>"本期九亩公社点菜成功", "color"=>"#173177"), 
									"keyword1" =>array("value"=>"$oid", "color"=>"#173177"),
									"keyword2" =>array("value"=>"$username", "color"=>"#173177"),
									"keyword3" =>array("value"=>"$address", "color"=>"#173177"),
									"keyword4" =>array("value"=>"会员内消费", "color"=>"#173177"),
									"keyword5" =>array("value"=>"$this->sendTime", "color"=>"#173177"),
									"remark"   =>array("value"=>"一共".$totalnum."份，将尽快送达！", "color"=>"#173177"),
						)
		);
		$weObj = new \Org\Util\Wechat();
		$msg_result = $weObj->sendTemplateMessage($data);
		*/
		// 接入模板消息模块
		$dataTime = date("Y-m-d H:m", $addtime);
		$data = array("touser"=>"$this->openid",
						"template_id"=>"MEXY0oucG4fT-KFyvFjh_IOa1y29t3vX_R-dwviALlo",
						"url"=> 'http://'.$_SERVER['HTTP_HOST'].U('Wap/OrderFood/myOrder'),
						"topcolor"=>"#FF0000",
						"data"=> serialize(array( "first"=>array("value"=>"谢谢您！订购本公众号产品！", "color"=>"#173177"), 
									"keyword1" =>array("value"=>"$dataTime", "color"=>"#173177"),
									"keyword2" =>array("value"=>"浙江省乐清市北白象镇正泰路1号", "color"=>"#173177"),
									"remark"   =>array("value"=>"一共".$totalnum.C('pom_unit')."，将尽快送达！", "color"=>"#173177"),
						)),
						'type' => 1,
		);
		\Think\Log::write('http://'.$_SERVER['HTTP_HOST'].'/WXATCenter/index.php/Wap/WXTemplateMsg/createMsg');
		$res = httpPostForGeneral('http://'.$_SERVER['HTTP_HOST'].'/WXATCenter/index.php/Wap/WXTemplateMsg/createMsg', $data);
		\Think\Log::write("给模板消息模块队列添加消息 结果：". dump($res, false));
		
		$this->display('info');
	}
	
	// 展示我的订单
	public function myOrder() {
		\Think\Log::write("我的订单！！！");
		$condition = "tp_order.openid = '$this->openid'";
		$orderList =  M('order')->join('tp_wxuser ON tp_order.openid = tp_wxuser.openid')->where($condition)->order('addtime desc')->select();
		foreach($orderList as $key => $order) {
			$order['postTime'] = $this->getSendTime($order['addtime']);
			$order['info'] = unserialize($order['ofoods']);
			
			$foodsTotal = 0;
			foreach($order['info'] as $food) {
				$foodsTotal += $food['num'];
			}
			$order['foodTotal'] = $foodsTotal;
			$orderList[$key] = $order;
		}
		$this->assign('orderList', $orderList);
		$this->assign('metaTitle', '订单详情');
		
		$this->display();
	}
	
	public function getSendTime($time) {
		$d = date('w', $time);
		switch($d) {
			case 0:
				return '下周一配送';
				break;
			case 1:
				return '当周四配送';
				break;
			case 2:
				return '当周四配送';
				break;
			case 3:
				return '当周四配送';
				break;
			case 4:
				return '下周一配送';
				break;
			case 5:
				return '下周一配送';
				break;
			case 6:
				return '下周一配送';
				break;
		}
	}
	
	// 检查是否是点菜的时间段
	public function chkSendTime() {
		$d = date('w');
		switch($d) {
			case 0:
				$this->canOrder = true;		//$this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (36*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 1:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 2:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 3:
				$this->canOrder = true;		//$this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (48*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 4:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 5:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 6:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (48*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
		}
	}
	
	public function chkSendTime_2() {
		$d = date('w');
		switch($d) {
			case 0:
				$this->canOrder = $this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
			case 1:
				$this->canOrder = false;
				break;
			case 2:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 3:
				$this->canOrder = $this->chkAM();
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec - (24*3600);
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周四开始配送";
				break;
			case 4:
				$this->canOrder = false;
				break;
			case 5:
				$this->canOrder = false;
				break;
			case 6:
				$this->canOrder = true;
				$today = date("Y-m-d");
				$zero_clock_sec  = strtotime($today);
				$now_clock_sec   = time(date("Y-m-d"));
				$this->startTime 	= $zero_clock_sec;
				$this->endTime 		= $now_clock_sec;
				$this->sendTime		= "将于周一开始配送";
				break;
		}
	}
	
	// 判断是否是上午
	public function chkAM() {
		$today = date("Y-m-d");
		$zero_clock_sec  = strtotime($today);
		$now_clock_sec   = time(date("Y-m-d"));
		if ($now_clock_sec < $zero_clock_sec + (24*3600)) {	// change
			return true;
		}else {
			return false;
		}
	}
	
	// 判断是否已经订餐
	public function hasOrder() {
		$condition = array();
		$condition['addtime'] 	= array('between', "$this->startTime, $this->endTime");
		$condition['openid'] 	= $this->openid;
		
		$res = M('order')->where($condition)->select();
		if(empty($res)) {
			return false;
		} else {
			return true;
		}
	}
	
	// 检查是否可以允许点菜，在这个时间范围内
	public function timeOKCheck() {
		$this->chkSendTime();
		if(!$this->canOrder) {
			$this->assign('title', "提示");
			$this->assign('msg', "非订餐时间");
			$this->assign('icontype', C('ICON_CLOSE'));
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit();
		}
		// 提示是否
		if($this->hasOrder()) {
			$this->assign('title', "提示");
			$this->assign('icontype', C('ICON_DONE'));
			$this->assign('msg', "本期您已点菜");
			$this->assign('signpackage', $this->signpackage);
			$this->display('info');
			exit();
		}
	}
}
?>